#include "MIBSKeyTrans.h"

void MIBSKeyTrans( FILE* infp , int round , FILE* outfp )
{
	char getin = 0 ;
	int increase = 0 ;
	int index = 0 ;
	bool iswrite = 0 ;
	bool isnum = 0 ;
	bool ispos = 0 ;
	for ( int i = 3 ; i <= round ; ++i )
	{
		char round_array[5] = { 0 } ;
		int round_counter = 0 ;
		int compared_pos = 64*(i-2)+15 ;
		for ( int j = 0 ; j < 5 ; ++j )
		{
			round_array[j] = (i >> j) & 0x01 ;
		}
		while ( (getin=fgetc(infp)) != EOF )
		{
			if ( getin == 's' )
			{
				iswrite = 1 ;
				increase = 64 ;
				fputc( getin , outfp ) ;
				isnum = 1 ;
			}
			else if ( getin == 'k' )
			{
				iswrite = 0 ;
				increase = 32 ;
				fputc( getin , outfp ) ;
				isnum = 1 ;
			}
			else if ( ((getin >= '0')&&(getin <= '9'))&&(isnum == 1) )
			{
				index = index*10 + getin - '0' ;
			}
			else if ( getin == ']' )
			{
				index = index + increase*(i-2) ;
				if ( (index >= (compared_pos+12))&&(index <= (compared_pos+16))&&(iswrite != 0) )
				{
					ispos = 1 ;
				}
				isnum = 0 ;
				fprintf( outfp , "%d" , index ) ;
				fputc( getin , outfp ) ;
			}
			else
			{
				if ( ((getin == '0')||(getin == '1')) )
				{
					if ( (ispos == 1) )
					{
						ispos = 0 ;
						fprintf( outfp , "%d" , round_array[round_counter] ) ;
						round_counter = round_counter + 1;
					}
					else
					{
						fputc( getin , outfp ) ;
					}					
				}
				else
				{
					fputc( getin , outfp ) ;
				}
				index = 0 ;
			}
		}
		fprintf( outfp , "\n" ) ;
		fseek( infp , 0L , SEEK_SET ) ;
	}
}